package com.electric.qrapp.ui.file.newfile

import androidx.lifecycle.MutableLiveData
import com.electric.qrapp.entity.bean.FilePreviewModel
import com.electric.qrapp.entity.init.RxhttpInitializer
import com.electric.qrapp.net.rxhttp.ErrorUtils
import com.electric.qrapp.ui.base.repo.BaseRepository
import com.electric.qrapp.utils.data.DataManager
import com.electric.qrapp.utils.function.GsonUtils
import com.electric.qrapp.utils.function.getFileType
import com.electric.qrapp.utils.system.Constants
import com.electric.qrapp.utils.system.showLog
import com.electric.qrapp.utils.system.showToast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import rxhttp.awaitResult
import rxhttp.timeout
import rxhttp.toDownload
import rxhttp.wrapper.param.RxHttp
import java.io.File
import javax.inject.Inject

/**
 *@author created by WA03675
 *@date  2022-04-01 14:52
 *@des
 */
class NewFileRepository @Inject constructor() : BaseRepository() {
    /**
     *文件预览
     * @param url
     * @param vmPreview
     */
    suspend fun getFile(coroutineScope: CoroutineScope, url: String, vmPreview: MutableLiveData<FilePreviewModel>) {
        val files = File(Constants.File.FILE_CACHE)

        if (getFileType(url) === null) {
            showToast(msg = "打开文件失败,原因:未知文件类型!")
            return
        }


        if (!files.exists()) {
            files.mkdir()
        }

        var fileName = url
            .replace("/", "")
            .replaceFirst(":", "")

        val file = File(files, "$fileName")

        //有缓存文件
        if (DataManager.isHaveFile(file.absolutePath)) {
            getFileSuccess(coroutineScope, file.absolutePath, url, vmPreview)
        } else {
            RxHttp.get(url)
                .toDownload(file.absolutePath)
                .timeout(RxhttpInitializer.FileDownOut)
                .awaitResult {
                    getFileSuccess(coroutineScope, it, url, vmPreview)
                }.onFailure {
                    vmPreview.postValue(FilePreviewModel("", "", false, it.toString()))
                    ErrorUtils.getError(it)
                }
        }
    }

    private fun getFileSuccess(coroutineScope: CoroutineScope, filePath: String, url: String, vmPreview: MutableLiveData<FilePreviewModel>) {
        coroutineScope.launch {
            DataManager.setCacheFileList(filePath)
            vmPreview.postValue(FilePreviewModel(filePath, getFileType(url)!!, true, ""))
        }

    }
}